<template>
    <div class="comment-management-container">
      <!-- 搜索和筛选区域 -->
      <div class="filter-container">
        <el-form :inline="true" :model="queryParams" class="demo-form-inline">
          <el-form-item label="评论内容">
            <el-input v-model="queryParams.content" placeholder="请输入评论内容" clearable />
          </el-form-item>
          <el-form-item label="用户">
            <el-input v-model="queryParams.username" placeholder="请输入用户名" clearable />
          </el-form-item>
          <el-form-item label="关联内容ID">
            <el-input v-model="queryParams.contentid" placeholder="请输入内容ID" clearable />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="审核状态">
            <el-select v-model="queryParams.auditstatus" placeholder="请选择审核状态" clearable>
              <el-option
                v-for="item in auditStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="评论时间">
            <el-date-picker
              v-model="queryParams.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
  
      <!-- 操作按钮区域 -->
      <div class="operation-container">
        <el-button type="danger" :disabled="!selectedIds.length" @click="handleBatchDelete">
          批量删除
        </el-button>
        <el-button type="warning" :disabled="!selectedIds.length" @click="handleBatchAudit(4)">
          批量违规
        </el-button>
        <el-button type="success" :disabled="!selectedIds.length" @click="handleBatchAudit(1)">
          批量通过
        </el-button>
        <el-button type="info" @click="handleExport">
          导出数据
        </el-button>
        <el-button type="primary" @click="handleCheckSensitiveWords">
          敏感词检测
        </el-button>
      </div>
  
      <!-- 表格区域 -->
      <div class="table-container">
        <el-table
          ref="tableRef"
          v-loading="loading"
          :data="commentList"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column prop="id" label="ID" width="80" align="center" sortable />
          <el-table-column label="用户" width="150" align="center">
            <template #default="{ row }">
              <div class="user-info-cell" @click="handleShowUserInfo(row.userid)">
                <el-avatar :src="row.avatar" />
                <div class="user-info">
                  <div class="username">{{ row.username}}</div>
                  <div class="user-level">
                    <el-tag v-if="row.userverified" size="small" type="success">V</el-tag>
                    <el-tag size="small">Lv.{{ row.userlevel }}</el-tag>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="评论内容" min-width="300">
            <template #default="{ row }">
              <div class="comment-content">
                <div v-if="row.replyusername" class="reply-info">
                  回复 <el-tag size="small">{{ row.replyusername }}</el-tag>:
                </div>
                <div class="content-text">{{ row.content }}</div>
                <div v-if="row.imageid" class="comment-image">
                  <el-image
                    :src="row.imageid"
                    fit="cover"
                    :preview-src-list="[row.imageid]"
                    style="width: 100px; height: 100px; border-radius: 4px;"
                  />
                </div>
                <div v-if="row.atusers && row.atusers.length" class="at-users">
                  <el-tag
                    v-for="user in row.atusers"
                    :key="user.userid"
                    size="small"
                    type="info"
                    style="margin-right: 5px;"
                  >
                    @{{ user.name }}
                  </el-tag>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="关联内容" width="120" align="center">
            <template #default="{ row }">
              <el-tag @click="handleViewContent(row.contentid)">
                ID: {{ row.contentid }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="120" align="center">
            <template #default="{ row }">
              <el-tag :type="statusMap[row.status].type">
                {{ statusMap[row.status].label }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="审核" width="120" align="center">
            <template #default="{ row }">
              <el-tag :type="auditStatusMap[row.auditstatus].type">
                {{ auditStatusMap[row.auditstatus].label }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="likes" label="点赞" width="90" align="center" sortable />
          <el-table-column prop="replycount" label="回复" width="90" align="center" sortable />
          <el-table-column prop="createtime" label="评论时间" width="180" align="center" sortable>
            <template #default="{ row }">
              <!-- {{ formatTime(row.createtime) }} -->
              {{ row.createtime }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right" align="center">
            <template #default="{ row }">
              <el-button size="small" type="primary" @click="handleEdit(row)">
                编辑
              </el-button>
              <el-dropdown trigger="click" @command="handleCommand($event, row)">
                <el-button size="small">
                  更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="delete">删除</el-dropdown-item>
                    <el-dropdown-item v-if="row.status !== 2" command="auditPass">审核通过</el-dropdown-item>
                    <el-dropdown-item v-if="row.status !== 4" command="auditReject">标记违规</el-dropdown-item>
                    <el-dropdown-item command="viewReplies">查看回复</el-dropdown-item>
                    <el-dropdown-item command="viewHistory">编辑历史</el-dropdown-item>
                    <el-dropdown-item command="ipInfo">IP信息</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>
  
      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
  
      <!-- 编辑评论对话框 -->
      <el-dialog
        v-model="editDialogVisible"
        :title="`编辑评论(ID: ${currentComment.id})`"
        width="50%"
        destroy-on-close
      >
        <el-form :model="commentForm" label-width="80px">
          <el-form-item label="评论内容">
            <el-input
              v-model="commentForm.content"
              type="textarea"
              :rows="5"
              placeholder="请输入评论内容"
            />
          </el-form-item>
          <el-form-item label="敏感词检测">
            <el-tag
              v-for="word in sensitiveWords"
              :key="word.word"
              type="danger"
              style="margin-right: 10px;"
            >
              {{ word.word }} ({{ word.type | sensitiveTypeFilter }})
            </el-tag>
            <el-button size="small" @click="handleCheckSensitiveWordsForCurrent">
              重新检测
            </el-button>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="commentForm.status" placeholder="请选择状态">
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="审核状态">
            <el-select v-model="commentForm.auditstatus" placeholder="请选择审核状态">
              <el-option
                v-for="item in auditStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSaveComment">
              保存
            </el-button>
          </span>
        </template>
      </el-dialog>
  
      <!-- 用户信息对话框 -->
      <el-dialog
        v-model="userInfoVisible"
        title="用户信息"
        width="50%"
        destroy-on-close
      >
        <user-info :user-id="currentUserId" />
      </el-dialog>
  
      <!-- 审核对话框 -->
      <el-dialog
        v-model="auditDialogVisible"
        :title="`${auditAction === 1 ? '通过' : '驳回'}审核`"
        width="50%"
        destroy-on-close
      >
        <el-form :model="auditForm" label-width="80px">
          <el-form-item label="审核意见">
            <el-input
              v-model="auditForm.reason"
              type="textarea"
              :rows="4"
              placeholder="请输入审核意见"
            />
          </el-form-item>
          <el-form-item v-if="auditAction === 4" label="违规原因">
            <el-select v-model="auditForm.violationType" placeholder="请选择违规类型">
              <el-option
                v-for="item in violationOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="auditDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleConfirmAudit">
              确认
            </el-button>
          </span>
        </template>
      </el-dialog>
  
      <!-- IP信息对话框 -->
      <el-dialog
        v-model="ipInfoVisible"
        title="IP信息"
        width="40%"
        destroy-on-close
      >
        <el-descriptions :column="1" border>
          <el-descriptions-item label="IP地址">{{ currentIpInfo.ipaddress }}</el-descriptions-item>
          <el-descriptions-item label="地理位置">{{ currentIpInfo.iplocation }}</el-descriptions-item>
          <el-descriptions-item label="设备类型">{{ currentIpInfo.device }}</el-descriptions-item>
          <el-descriptions-item label="操作系统">{{ currentIpInfo.os }}</el-descriptions-item>
          <el-descriptions-item label="APP版本">{{ currentIpInfo.appversion }}</el-descriptions-item>
        </el-descriptions>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { ArrowDown } from '@element-plus/icons-vue'
  import request from '../utils/request';
  //import { formatTime } from '@/utils/date'
//   import {
//     getCommentList,
//     updateComment,
//     deleteComment,
//     auditComment,
//     batchAuditComment,
//     checkSensitiveWords
//   } from '@/api/comment'
  
  // 状态映射
  const statusMap = {
    1: { label: '正常', type: 'success' },
    2: { label: '已删除', type: 'danger' },
    3: { label: '审核中', type: 'warning' },
    4: { label: '违规', type: 'danger' }
  }
  
  // 审核状态映射
  const auditStatusMap = {
    0: { label: '未审核', type: 'info' },
    1: { label: '已审核', type: 'success' },
    2: { label: '需复审', type: 'warning' }
  }
  
  // 状态选项
  const statusOptions = [
    { value: 1, label: '正常' },
    { value: 2, label: '已删除' },
    { value: 3, label: '审核中' },
    { value: 4, label: '违规' }
  ]
  
  // 审核状态选项
  const auditStatusOptions = [
    { value: 0, label: '未审核' },
    { value: 1, label: '已审核' },
    { value: 2, label: '需复审' }
  ]
  
  // 违规类型选项
  const violationOptions = [
    { value: 1, label: '政治敏感' },
    { value: 2, label: '色情低俗' },
    { value: 3, label: '暴力恐怖' },
    { value: 4, label: '垃圾广告' },
    { value: 5, label: '人身攻击' },
    { value: 6, label: '侵犯隐私' },
    { value: 7, label: '其他违规' }
  ]
  
  // 敏感词类型过滤
  const sensitiveTypeFilter = (type) => {
    const map = {
      1: '政治',
      2: '色情',
      3: '暴力',
      4: '广告',
      5: '辱骂',
      6: '其他'
    }
    return map[type] || '未知'
  }
  
  // 查询参数
  const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    content: '',
    username: '',
    contentid: '',
    status: undefined,
    auditstatus: undefined,
    dateRange: []
  })
  
  // 表格数据
  const commentList = ref([])
  const loading = ref(false)
  const total = ref(0)
  const selectedIds = ref([])
  
  // 对话框控制
  const editDialogVisible = ref(false)
  const userInfoVisible = ref(false)
  const auditDialogVisible = ref(false)
  const ipInfoVisible = ref(false)
  const currentComment = ref({})
  const currentUserId = ref(null)
  const currentIpInfo = ref({})
  const auditAction = ref(1) // 1通过 4违规
  const sensitiveWords = ref([])
  
  // 表单数据
  const commentForm = reactive({
    id: '',
    content: '',
    status: 1,
    auditstatus: 0
  })
  
  const auditForm = reactive({
    reason: '',
    violationType: undefined
  })
  
  // 获取评论列表
  const getList = async () => {
    try {
      loading.value = true
      const params = {
        ...queryParams,
        startTime: queryParams.dateRange?.[0],
        endTime: queryParams.dateRange?.[1]
      }
      delete params.dateRange
      
      //const res = await getCommentList(params)
      const res = await  request.post('/xhs/talk/getTalkList',params)  
      commentList.value = res.data.records
      total.value = res.data.total
    } catch (error) {
      console.error('获取评论列表失败:', error)
    } finally {
      loading.value = false
    }
  }
  
  // 搜索
  const handleQuery = () => {
    queryParams.pageNum = 1
    getList()
  }
  
  // 重置搜索
  const resetQuery = () => {
    queryParams.pageNum = 1
    queryParams.content = ''
    queryParams.username = ''
    queryParams.contentid = ''
    queryParams.status = undefined
    queryParams.auditstatus = undefined
    queryParams.dateRange = []
    getList()
  }
  
  // 分页大小改变
  const handleSizeChange = (val) => {
    queryParams.pageSize = val
    getList()
  }
  
  // 当前页改变
  const handleCurrentChange = (val) => {
    queryParams.pageNum = val
    getList()
  }
  
  // 表格行选择
  const handleSelectionChange = (selection) => {
    selectedIds.value = selection.map(item => item.id)
  }
  
  // 编辑评论
  const handleEdit = (row) => {
    currentComment.value = { ...row }
    commentForm.id = row.id
    commentForm.content = row.content
    commentForm.status = row.status
    commentForm.auditstatus = row.auditstatus
    sensitiveWords.value = row.sensitivewords || []
    editDialogVisible.value = true
  }
  
  // 保存评论
  const handleSaveComment = async () => {
    try {
      //await updateComment(commentForm)
      ElMessage.success('保存成功')
      editDialogVisible.value = false
      getList()
    } catch (error) {
      console.error('保存评论失败:', error)
    }
  }
  
  // 删除评论
  const handleDelete = (row) => {
    ElMessageBox.confirm(`确认删除这条评论吗?`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        //await deleteComment(row.id)
        const res = await  request.post('/xhs/talk/deleteTalkById',{"id":row.id})  
        ElMessage.success('删除成功')
        getList()
      } catch (error) {
        console.error('删除失败:', error)
      }
    }).catch(() => {})
  }
  
  // 批量删除
  const handleBatchDelete = () => {
    if (!selectedIds.value.length) return
    
    ElMessageBox.confirm(`确认删除选中的${selectedIds.value.length}条评论吗?`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        //await deleteComment(selectedIds.value.join(','))
        ElMessage.success('批量删除成功')
        selectedIds.value = []
        getList()
      } catch (error) {
        console.error('批量删除失败:', error)
      }
    }).catch(() => {})
  }
  
  // 审核评论
  const handleAudit = (id, action) => {
    currentComment.value = { id }
    auditAction.value = action
    auditForm.reason = ''
    auditForm.violationType = undefined
    auditDialogVisible.value = true
  }
  
  // 批量审核
  const handleBatchAudit = (action) => {
    if (!selectedIds.value.length) return
    
    currentComment.value = { id: null }
    auditAction.value = action
    auditForm.reason = ''
    auditForm.violationType = undefined
    auditDialogVisible.value = true
  }
  
  // 确认审核
  const handleConfirmAudit = async () => {
    try {
      const params = {
        ids: currentComment.value.id ? [currentComment.value.id] : selectedIds.value,
        status: auditAction.value === 1 ? 1 : 4,
        reason: auditForm.reason,
        violationType: auditForm.violationType
      }
      
      if (currentComment.value.id) {
        //await auditComment(currentComment.value.id, params)
      } else {
       // await batchAuditComment(params)
      }
      
      ElMessage.success('操作成功')
      auditDialogVisible.value = false
      selectedIds.value = []
      getList()
    } catch (error) {
      console.error('审核操作失败:', error)
    }
  }
  
  // 显示用户信息
  const handleShowUserInfo = (userId) => {
    currentUserId.value = userId
    userInfoVisible.value = true
  }
  
  // 查看关联内容
  const handleViewContent = (contentId) => {
    console.log('查看关联内容:', contentId)
    ElMessage.success('查看内容功能待开发')
  }
  
  // 敏感词检测
  const handleCheckSensitiveWords = async () => {
    try {
      const ids = selectedIds.value.length ? selectedIds.value : commentList.value.map(item => item.id)
      if (!ids.length) {
        ElMessage.warning('请选择评论或确保列表中有数据')
        return
      }
      
      //const res = await checkSensitiveWords(ids)
      ElMessage.success(`检测完成，发现 ${res.data.total} 条评论包含敏感词`)
      getList()
    } catch (error) {
      console.error('敏感词检测失败:', error)
    }
  }
  
  // 检测当前评论的敏感词
  const handleCheckSensitiveWordsForCurrent = async () => {
    try {
      //const res = await checkSensitiveWords([commentForm.id])
      const res = ref("");
      sensitiveWords.value = res.data.words || []
      if (sensitiveWords.value.length) {
        ElMessage.warning(`发现 ${sensitiveWords.value.length} 个敏感词`)
      } else {
        ElMessage.success('未发现敏感词')
      }
    } catch (error) {
      console.error('敏感词检测失败:', error)
    }
  }
  
  // 显示IP信息
  const handleShowIpInfo = (row) => {
    currentIpInfo.value = {
      ipaddress: row.ipaddress,
      iplocation: row.iplocation,
      device: row.device,
      os: row.os,
      appversion: row.appversion
    }
    ipInfoVisible.value = true
  }
  
  // 更多操作
  const handleCommand = (command, row) => {
    switch (command) {
      case 'delete':
        handleDelete(row)
        break
      case 'auditPass':
        handleAudit(row.id, 1)
        break
      case 'auditReject':
        handleAudit(row.id, 4)
        break
      case 'viewReplies':
        handleViewReplies(row)
        break
      case 'viewHistory':
        handleViewHistory(row)
        break
      case 'ipInfo':
        handleShowIpInfo(row)
        break
      default:
        break
    }
  }
  
  // 查看回复
  const handleViewReplies = (row) => {
    queryParams.parentid = row.id
    handleQuery()
  }
  
  // 查看编辑历史
  const handleViewHistory = (row) => {
    console.log('查看编辑历史:', row.id)
    ElMessage.success('编辑历史功能待开发')
  }
  
  // 导出数据
  const handleExport = () => {
    console.log('导出数据')
    ElMessage.success('导出功能待开发')
  }
  
  // 初始化
  onMounted(() => {
    getList()
  })
  </script>
  
  <style lang="scss" scoped>
  .comment-management-container {
    padding: 20px;
    
    .filter-container {
      margin-bottom: 20px;
      padding: 20px;
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    }
    
    .operation-container {
      margin-bottom: 20px;
      padding: 10px 20px;
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    }
    
    .table-container {
      margin-bottom: 20px;
      padding: 20px;
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
      
      :deep(.el-table) {
        .user-info-cell {
          display: flex;
          align-items: center;
          cursor: pointer;
          
          .el-avatar {
            margin-right: 10px;
          }
          
          .user-info {
            .username {
              font-weight: 500;
              margin-bottom: 5px;
            }
            
            .user-level {
              display: flex;
              gap: 5px;
              
              .el-tag {
                height: 20px;
                line-height: 20px;
              }
            }
          }
          
          &:hover {
            color: var(--el-color-primary);
          }
        }
        
        .comment-content {
          .reply-info {
            margin-bottom: 5px;
            color: #666;
            font-size: 12px;
          }
          
          .content-text {
            margin-bottom: 10px;
            line-height: 1.6;
          }
          
          .comment-image {
            margin-bottom: 10px;
          }
          
          .at-users {
            margin-top: 5px;
          }
        }
      }
    }
    
    .pagination-container {
      display: flex;
      justify-content: flex-end;
      padding: 10px 20px;
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    }
  }
  </style>